<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Menu extends Controller_Admin_Layout
{
	public function __construct($request, $response){
		parent::__construct($request, $response);
	}
	
	public function action_index($id = null){
		
		if(Request::current()->method() === 'POST'){
			
			$formData = Arr::extract($_POST,array('name','active','link','parent_id','id','target','target_id','position'));
			
			$valid = Validation::factory($formData)
									->rule('name', 'not_empty');
			if($valid->check()){
				if(is_null($formData['id'])){
					$result = $this->create($formData);
				}else{
					$result = $this->update($formData);
				}	
			}else{
				FlashMessage::getInstance()->add($valid->errors('menu','true'),FlashMessage::ERROR,true);
			}
			
		}
		
		if(is_null($id)){
			$menu = Libs_Menu::getInstance()->getRoot();
		}else{
			$menu = Libs_Menu::getInstance()->getMenuById($id);
		}
        
		$this->set_content(View::admin('menu/index')->set(array(
			'form' => View::admin('menu/form')->set(array(
				'menu' => new Menu(),
				'id' => $id,
                'target' => $menu->getNode()->getChildren()
			)),
			'list' => View::admin('menu/list')->set(array(
				'root' => $menu
			)),
			'menu' => $menu
		)));	
	}

	public function action_edit($id = null){
		
		if(is_null($id)){
			$this->response->status(404);
		}else{
			$menu = Libs_Menu::getInstance()->getMenuById($id);
			$this->set_content(View::admin('menu/edit')->set(array(
				'form' => View::admin('menu/form')->set(array(
					'menu' => ($menu) ? $menu : new Menu(),
                    'target' => ($menu) ? $menu->getNode()->getParent()->getNode()->getChildren() : false
				))
			)));
		}
	}
	
	public function action_delete($id){
		$this->delete($id);
		$this->request->redirect(Route::url('menu-list'));
	}
	
	public function action_update(){
		if(Request::current()->method() === 'POST')
		{
			$ids = Arr::get($_POST,'menu_ids');
			
			switch (Arr::get($_POST, 'action')) 
			{
				case 'active':
					break;
				case 'inactive':
					break;
				case 'delete':
					$this->delete($ids);
					break;
			}
		}
	}
    
    private function create($formData){
		return Libs_Menu::getInstance()->createNewMenuItem($formData);
	}
	
	private function update($formData){
		return Libs_Menu::getInstance()->updateMenuIitem($formData);
	}
	
	private function delete($ids){
		$qDelete = Doctrine_Query::create()
									->delete('Menu m');
									
		if(is_array($ids)){
			$qDelete->whereIn('m.id',$ids);
		}else{
			$qDelete->where('m.id = ?',$ids);
		}
		
		return $qDelete->execute();
		
	}
}
